//
//  XQShowCoverController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/19.
//

#import "XQShowCoverController.h"
#import "XQHomeTabBarController.h"
#import "XQWelcomeController.h"
#import "XQLoginInitModel.h"
#import "XQToolManager.h"
#import "XQDevice.h"
#import "LLNetworkAccessibility.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>

@interface XQShowCoverController ()

@property (nonatomic,strong) UIImageView *bgImageView;

@property (nonatomic,strong) UIImageView *logoImageView;

@property (nonatomic,strong) UILabel *titleLb;

@property (nonatomic,strong) UIButton *joinButton;

@property (nonatomic, assign) BOOL hasDined;

@property (nonatomic, assign) BOOL isFirstLoad;

@end

@implementation XQShowCoverController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeUI];
    [self makeConstraints];
    
    id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"isNetFirstLoad"];
    
    self.isFirstLoad = [value boolValue];
    
    // 网络权限
    [self startMonitoringNetwork];
    [self refreshDefaultUrl];
    
    [XQHUD showLoadingInView:self.view];
}

- (void)makeUI {
    [self.view addSubview:self.bgImageView];
    [self.view addSubview:self.logoImageView];
    [self.view addSubview:self.titleLb];
    [self.view addSubview:self.joinButton];
}

- (void)makeConstraints {
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        (void)make.centerX;
        make.top.mas_equalTo([UIScreen mainScreen].statusBarHeight + 178);
        make.width.height.equalTo(@112);
    }];
    [self.titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        (void)make.centerX;
        make.top.equalTo(self.logoImageView.mas_bottom).offset(26);
    }];
    [self.joinButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.height.mas_equalTo(45);
        make.bottom.mas_equalTo(-[UIScreen mainScreen].bottomHeight - 119);
    }];
}

- (void)refreshDefaultUrl {
    @weakify(self);
    [XQAFNetworking getWithUrl:[XQNetManager getAbsolutePath:@""] pars:@{} callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        if (error) {
            @weakify(self);
            [self refreshJsonData:^(NSArray *urls) {
                @strongify(self);
                [self refreshDefaultJsonUrlWithIndex:0 urls:urls];
            }];
        }else {
            [self refreshInitData];
        }
    }];
}

- (void)refreshDefaultJsonUrlWithIndex:(NSInteger)index urls:(NSArray *)urls {
    
    if (urls.count > 0 && index >= urls.count) {
        [XQHUD hideLoadindInView:self.view];
        [XQToast showMsg:@"Network request error"];
        return;
    }
    
    NSString *url = [urls[index] description];
    if (url.length) {
        [XQNetManager sharedInstance].url = url;
    }
    
    @weakify(self);
    [XQAFNetworking getWithUrl:[XQNetManager getAbsolutePath:@""] pars:@{} callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        if (error) {
            [self refreshDefaultJsonUrlWithIndex:index + 1 urls:urls];
        }else {
            [self refreshInitData];
        }
    }];
}

- (void)refreshInitData {
    NSDictionary *parametersDic = @{
        @"flare" : @"en",
        @"stratosphere" : @(0),
        @"balloons" : @(0),
    };

    @weakify(self);
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/flare"] pars:parametersDic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if (error == nil && [responseObject[@"concept"] integerValue] == 0) {
            XQLoginInitModel *model = [XQLoginInitModel yy_modelWithDictionary:responseObject];
            
            [XQToolManager manager].model = model;
            
            [[XQNetManager sharedInstance].globalDic setValue:@(model.accomplish.lynk) forKey:@"lynk"];
                    
            if (model.conceptStatus == 0) {
                FBSDKSettings.sharedSettings.appID = model.accomplish.distress.entire;
                FBSDKSettings.sharedSettings.displayName = model.accomplish.distress.landmass;
                FBSDKSettings.sharedSettings.clientToken = model.accomplish.distress.covering;
                FBSDKSettings.sharedSettings.appURLSchemeSuffix = model.accomplish.distress.nautical;
                FBSDKSettings.sharedSettings.isAutoLogAppEventsEnabled = true;
                [[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication] didFinishLaunchingWithOptions:self.launchOptions];
            }
            
            [self jump];
            
            [self refreshCityData];
            
            [XQGoogleMarket reportDevice];
            
            // 定位权限
            [[XQLocationManager manager] startLocation];
        }else {
            @weakify(self);
            [self refreshJsonData:^(NSArray *urls) {
                @strongify(self);
                [self refreshInitJsonData:0 urls:urls];
            }];
        }
    }];
}

- (void)refreshInitJsonData:(NSInteger)index urls:(NSArray *)urls {
    NSDictionary *parametersDic = @{
        @"flare" : @"en",
        @"stratosphere" : @(0),
        @"balloons" : @(0),
    };
    
    if (urls.count > 0 && index >= urls.count) {
        [XQHUD hideLoadindInView:self.view];
        [XQToast showMsg:@"Network request error"];
        return;
    }
    
    NSString *url = [urls[index] description];
    if (url.length) {
        [XQNetManager sharedInstance].url = url;
    }
    
    @weakify(self);
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/flare"] pars:parametersDic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        if (error) {
            [self refreshInitJsonData:index + 1 urls:urls];
        }else {
            [self refreshInitData];
        }
    }];
}

- (void)refreshJsonData:(void (^)(NSArray *urls))completion {
    @weakify(self);
    [XQAFNetworking getWithUrl:@"https://ph01-dc.oss-ap-southeast-6.aliyuncs.com/join-peso/jp.json" pars:@{} callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        if (error == nil) {
            if ([responseObject isKindOfClass:[NSArray class]]) {
                NSMutableArray *urls = [NSMutableArray array];
                for (NSDictionary *dic in responseObject) {
                    [urls addObject:dic[@"jp"]];
                }
                completion(urls);
            }
        }else {
            [XQHUD hideLoadindInView:self.view];
//            if (self.isFirstLoad) {
//                [XQToast showMsg:@"Network request error"];
//            }else {
//                self.isFirstLoad = YES;
//                [[NSUserDefaults standardUserDefaults] setObject:@(1) forKey:@"isNetFirstLoad"];
//            }
            [XQToast showMsg:@"Network request error"];
        }
    }];
}

#pragma mark - public

- (void)jump {
    BOOL showGuide = [[NSUserDefaults standardUserDefaults] objectForKey:@"showGuide"];
    
    if (!showGuide) {
        XQWelcomeController *mainVC = [[XQWelcomeController alloc] init];
        [self.navigationController setViewControllers:@[mainVC] animated:NO];
    }else {
        XQHomeTabBarController *mainVC = [[XQHomeTabBarController alloc] init];
        [self.navigationController setViewControllers:@[mainVC] animated:NO];
    }
}

#pragma mark - private

- (void)startMonitoringNetwork {
    [LLNetworkAccessibility stop];
    [LLNetworkAccessibility start];
    [LLNetworkAccessibility reachabilityUpdateCallBack:^(AuthType state) {
        switch (state) {
            case available:
                if ([XQToolManager manager].model == nil) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self refreshDefaultUrl];
                    });
                }
                break;
            case restricted:
                break;
            default:
                break;
        }
    }];
}

- (void)refreshCityData {
    [XQAFNetworking getWithUrl:[XQNetManager getAbsolutePath:@"/direct/telestra"] pars:@{} callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        if ([responseObject[@"concept"] integerValue] == 0) {
            NSDictionary *accomplish = responseObject[@"accomplish"];
            id rakuten = accomplish[@"rakuten"];
            if ([rakuten isKindOfClass:[NSArray class]]) {
                [[NSUserDefaults standardUserDefaults] setObject:rakuten forKey:@"KCitys"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
    }];
}

- (void)refreshTracking {
   id flag = [[NSUserDefaults standardUserDefaults] objectForKey:KXQTrackingInfo];
    BOOL value = [flag boolValue];
    
    if (value) {
        [XQGoogleMarket reportIdfv];
    }
}

- (void)joinClick {
    [self refreshDefaultUrl];
    [XQHUD showLoadingInView:self.view];
}

#pragma mark - lazy

- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] init];
        _bgImageView.image = [UIImage imageNamed:@"launch_bg"];
    }
    return  _bgImageView;
}

- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = [[UIImageView alloc] init];
        _logoImageView.image = [UIImage imageNamed:@"logo"];
    }
    return  _logoImageView;
}

- (UILabel *)titleLb {
    if (!_titleLb) {
        _titleLb = [[UILabel alloc] init];
        _titleLb.font = [UIFont boldSystemFontOfSize:27];
        _titleLb.text = @"JoinPeso";
        _titleLb.textColor = [UIColor colorWithHexString:@"#D8EBFF"];
    }
    return  _titleLb;
}

- (UIButton *)joinButton {
    if (!_joinButton) {
        _joinButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _joinButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [_joinButton setTitle:@"Try again" forState:UIControlStateNormal];
        [_joinButton setTitleColor:[UIColor colorWithHexString:@"#D8EBFF"] forState:UIControlStateNormal];
        _joinButton.backgroundColor = [UIColor colorWithHexString:@"#EB7B0F"];
        _joinButton.layer.cornerRadius = 22.5;
        [_joinButton addTarget:self action:@selector(joinClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _joinButton;
}

@end
